package proxy;

import sun.misc.ProxyGenerator;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.rmi.server.ExportException;

/**
 *
 */
public class JavaProxy implements InvocationHandler {
    private Dog target;
    public Dog getInstance(Dog target){
        this.target=target;
        Class clazz=target.getClass();
        return (Dog) Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result=method.invoke(this.target,args);
        after();
        return result;
    }

    private void after() {
        System.out.println("se");
    }

    private void before() {
    }

    public static void main(String[] args) {
        JavaProxy proxy=new JavaProxy();
        Dog dog=proxy.getInstance(new GunDog());
        dog.run();
        byte[] bytes=ProxyGenerator.generateProxyClass("$Proxy0",new Class[]{Dog.class});
        FileOutputStream os= null;
        try {
            os = new FileOutputStream("E://$Proxy0.class");
            os.write(bytes);
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
